package com.hopu.erp.controller;

import com.hopu.erp.entity.Functions;
import com.hopu.erp.service.FunctionsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Api
@RestController
public class FunctionsController {

    @Autowired
    private FunctionsService functionsService;

    @ApiOperation("这是按用户名查询权限的接口")
    @GetMapping("/functions/username")
    public ResponseEntity<List<Functions>> findFunctionsByUsername(){
        //从SpringSecurity取得登录的用户名
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(principal);
        User user = (User) principal;
        if(user != null){
            List<Functions> functions = functionsService.findFunctionsByUsername(user.getUsername());
            return ResponseEntity.ok(functions);
        }
        return null;
    }

    @ApiOperation("这是查询所有权限的接口")
    @GetMapping("/functions")
    public ResponseEntity<List<Functions>> findAllFunctions(){
        List<Functions> functions = functionsService.findAllFunctions();
        return ResponseEntity.ok(functions);
    }

    @ApiOperation("这是根据角色id查询所有权限的接口")
    @GetMapping("/functions/role/{roleId}")
    public ResponseEntity<List<Functions>> findFunctionsByRoleId(@PathVariable("roleId")Integer roleId){
        List<Functions> functions = functionsService.findFunctionsByRoleId(roleId);
        return ResponseEntity.ok(functions);
    }
}
